package com.kabigon.tiny.convert;

import com.kabigon.tiny.dto.ProductDto;
import com.kabigon.tiny.po.Product;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * 商品对象映射（自定义处理）
 * @author xu.biao
 * @version v1.0
 * @Package com.kabigon.tiny.convert
 * @data 2022/5/29 22:25
 */
@Mapper(imports = {UUID.class})
public interface ProductRoundConvert {
    ProductRoundConvert INSTANCE = Mappers.getMapper(ProductRoundConvert.class);

    @Mapping(target = "id", constant = "-1L")
    @Mapping(target = "count", defaultValue = "1")
    @Mapping(target = "productSn", expression = "java(UUID.randomUUID().toString())")
    public ProductDto toDto(Product product);

    @BeforeMapping
    public default void beforeMApping(Product product){
        //映射前当price<0时设置为0
        if (product.getPrice().compareTo(BigDecimal.ZERO) < 0) {
            product.setPrice(BigDecimal.ZERO);
        }
    }

    @AfterMapping
    public default void afterMapping(@MappingTarget ProductDto productDto){
        //映射后设置当前时间为createTime
        productDto.setCreateTime(new Date());
    }
}
